from flask import Blueprint, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from utils.response import success_response, error_response

device_bp = Blueprint('device', __name__)

# 模拟设备数据
DEVICES = [
    {
        "id": 1,
        "name": "智能灯泡",
        "type": "light",
        "status": True,
        "room": "客厅",
        "description": "客厅主灯"
    },
    {
        "id": 2,
        "name": "空调",
        "type": "air_conditioner",
        "status": False,
        "room": "卧室",
        "description": "卧室空调"
    },
    {
        "id": 3,
        "name": "智能门锁",
        "type": "lock",
        "status": True,
        "room": "门厅",
        "description": "入户门智能锁"
    }
]

@device_bp.route('/api/devices', methods=['GET'])
@jwt_required()
def get_devices():
    """获取设备列表"""
    try:
        return success_response(DEVICES)
    except Exception as e:
        print(f"获取设备列表错误: {str(e)}")
        return error_response("服务器内部错误", 500)

@device_bp.route('/api/device', methods=['POST'])
@jwt_required()
def add_device():
    """添加设备"""
    try:
        data = request.get_json()
        
        new_device = {
            "id": len(DEVICES) + 1,
            "name": data.get('name'),
            "type": data.get('type'),
            "status": data.get('status', False),
            "room": data.get('room'),
            "description": data.get('description', '')
        }
        
        DEVICES.append(new_device)
        return success_response(new_device, "设备添加成功")
        
    except Exception as e:
        print(f"添加设备错误: {str(e)}")
        return error_response("服务器内部错误", 500)

@device_bp.route('/api/device/<int:device_id>', methods=['PUT'])
@jwt_required()
def update_device(device_id):
    """更新设备"""
    try:
        data = request.get_json()
        
        # 查找设备
        device = next((d for d in DEVICES if d['id'] == device_id), None)
        if not device:
            return error_response("设备不存在", 404)
        
        # 更新设备信息
        device.update({
            "name": data.get('name', device['name']),
            "type": data.get('type', device['type']),
            "status": data.get('status', device['status']),
            "room": data.get('room', device['room']),
            "description": data.get('description', device['description'])
        })
        
        return success_response(device, "设备更新成功")
        
    except Exception as e:
        print(f"更新设备错误: {str(e)}")
        return error_response("服务器内部错误", 500)

@device_bp.route('/api/device/<int:device_id>', methods=['DELETE'])
@jwt_required()
def delete_device(device_id):
    """删除设备"""
    try:
        global DEVICES
        DEVICES = [d for d in DEVICES if d['id'] != device_id]
        return success_response(message="设备删除成功")
        
    except Exception as e:
        print(f"删除设备错误: {str(e)}")
        return error_response("服务器内部错误", 500)